// pages/checking/checking.js
// location_check_in/location_check_in.js
import sendRequest from '../rpromise/request'
const util = require('../qqmap/util')
const app = getApp()
const urlList = require("../qqmap/api.js") // 根据实际项目自己配置

// 实例化API核心类
const qqmapsdk = app.globalData.qqmapsdk

Page({

    /**
     * 页面的初始数据
     */
    data: {
        markers: '',
        poi: {
            latitude: '',
            longitude: ''
        },
        addressName: '',
        time: '',
        timer: '',
        timer2: '', // 用来每个一段时间自动刷新一次定位
        canClick: true,
        sno: '',
        ano: 0,
        sign: '',
    },

    getAddress(e) {
        var that = this;
        qqmapsdk.reverseGeocoder({
            //位置坐标，默认获取当前位置，非必须参数
            /**
             * 
              location: {
                latitude: 39.984060,
                longitude: 116.307520
              },
            */
            // 成功后的回调
            success: function (res) {
                // console.log(res);
                that.setData({
                    addressName: res.result.address
                })
                var res = res.result;
                var mks = [];
                //当get_poi为0时或者为不填默认值时，检索目标位置，按需使用
                mks.push({ // 获取返回结果，放到mks数组中
                    title: res.address,
                    id: 0,
                    latitude: res.location.lat,
                    longitude: res.location.lng,
                    iconPath: '/pages/images/myPosition.png', // 图标路径
                    width: 21,
                    height: 28,
                    callout: { //在markers上展示地址名称，根据需求是否需要
                        content: res.address,
                        color: '#000',
                        display: 'ALWAYS'
                    }
                });
                that.setData({ // 设置markers属性和地图位置poi，将结果在地图展示
                    markers: mks,
                    poi: {
                        latitude: res.location.lat,
                        longitude: res.location.lng
                    }
                });
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            }
        })
    },
    getTime: function () {
        let that = this
        let time = that.data.time
        that.setData({
            timer: setInterval(function () {
                time = util.formatTime(new Date())
                that.setData({
                    time: time.substr(-8)
                });
                if (time == 0) {
                    // 页面跳转后，要把定时器清空掉，免得浪费性能
                    clearInterval(that.data.timer)
                }
            }, 1000)
        })
    },
    rePosition: function () {
        // console.log('用户点了重新定位')
        this.getAddress()
    },
    checkIn: function () {
        this.setData({
            canClick: false
        })
        // console.log('用户点击了签到')
        var that = this
        var nowTime = util.formatTime(new Date())
        wx.showModal({
            title: '请确认打卡信息',
            // content: '请确认待整改项已整改完毕！',
            content: `地点：${this.data.addressName}\n时间：${nowTime}`, // 开发者工具上没有换行，真机调试时会有的
            confirmText: '确认',
            success(res) {
                if (res.confirm) {
                    // console.log('用户点击确定')
                    // 调起签到接口
                    that.realyCheckIn()

                } else if (res.cancel) {
                    // console.log('用户点击取消')
                    that.setData({
                        canClick: true
                    })
                }
            }
        })
    },
    async realyCheckIn() {
        var that = this
        var patrolForm = app.globalData.patrolForm // 其他需要一并提交过去的业务数据
        console.log(app.globalData)
        // debugger
        // 要在这里给 patrolForm 补充其他的参数
        patrolForm.address = this.data.addressName
        // 拼接："经度,纬度"
        var lat1 = this.data.poi.latitude
        var lng1 = this.data.poi.longitude
        console.log(lat1)
        // console.log("↑ 签到提交的post参数")
        var lat2 = 0.0
        var lng2 = 0.0
        var dis = 100.00
        var sql = "SELECT lat,lng,distance from activity WHERE ano=" + this.data.ano
        console.log(sql)
        var req = await this.sqlRequest(sql).then((res) => {
            lat2 = res.data[0].lat
            lng2 = res.data[0].lng
            dis = res.data[0].distance
        })
        console.log(lat2)
        var distance = this.getDistances(lat1, lng1, lat2, lng2)
        console.log(patrolForm)
        if (distance.distance_number <= dis && (distance.distance_str.indexOf('k') < 0)) {
            if (that.data.sign == '签到') {
                patrolForm.indistance = distance.distance_str
                patrolForm.incheck = 'Y'
                patrolForm.signintime = util.formatTime(new Date())
            }else{
                patrolForm.outdistance = distance.distance_str
                patrolForm.outcheck = 'Y'
                patrolForm.signouttime = util.formatTime(new Date())
            }
            var data = JSON.stringify(patrolForm).replace(/"(\w+)"\s*:/g, '$1:').replace(/[{}]/g, '').replace(/[:]/g, '=').replace(/(\d+)\s*=\s*(\d+)/g, "$1:$2").replace(/(\d+)\s*=\s*(\d+)/g, "$1:$2")
            var sql = "UPDATE sa SET " + data + " WHERE sno='" + this.data.sno + "' and ano=" + this.data.ano
            var req = this.sqlRequest(sql).then(res => {
                console.log(res)
                if (res.statusCode === 200) {
                    wx.showToast({
                        title: that.data.sign + '成功！',
                        icon: 'success',
                        duration: 2000,

                    })
                } else {
                    wx.showToast({
                        title: that.data.sign + '失败，请重试！',
                        icon: 'error',
                        duration: 2000,
                    })
                    this.setData({
                        canClick: true,
                    })
                }
            })

        } else {
            wx.showToast({
                title: that.data.sign + '失败，你未在规定范围内进行签到！',
                icon: 'none',
                duration: 2000,
                // complete: function () {
                //     wx.navigateBack({
                //         delta: 1
                //     })
                // }
            })
            this.setData({
                canClick: true,
            })
        }

    },
    async sqlRequest(sql) {
        console.log(sql)
        const res1 = await sendRequest({
            method: 'POST',
            url: '/manage',
            data: {
                sql: sql
            },
        })
        return res1
    },
    //计算方法
    rad(d) {
        return d * Math.PI / 180.0;
    },
    // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
    getDistances(lat1, lng1, lat2, lng2) {
        var radLat1 = this.rad(lat1);
        var radLat2 = this.rad(lat2);
        var a = radLat1 - radLat2;
        var b = this.rad(lng1) - this.rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        // 输出为公里
        s = Math.round(s * 10000) / 10000;
        var distance = s;
        var distance_str = "";
        var distance_number = 0.00
        if (parseInt(distance) >= 1) {
            distance_str = distance.toFixed(2) + "km";
            distance_number = distance.toFixed(2)
        } else {
            distance_str = (distance * 1000).toFixed(2) + "m";
            distance_number = (distance * 1000).toFixed(2)

        }
        let objData = {
            distance: distance,
            distance_str: distance_str,
            distance_number: parseFloat(distance_number)
        }
        console.log(objData)
        return objData
    },
    checkSign(){
        var sql = "SELECT incheck,outcheck FROM sa WHERE sno='"+this.data.sno+"' and ano="+this.data.ano
        this.sqlRequest(sql).then(res=>{
            console.log(res.data[0])
            if(res.data[0].incheck==='Y'&&this.data.sign==='签到'){
                this.setData({
                    canClick:false
                })
            }
            if(res.data[0].outcheck==='Y'&&this.data.sign==='签退'){
                this.setData({
                    canClick:false
                })
            }
        })
        
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this
        that.getTime()
        that.getAddress()
        that.setData({
            sno: wx.getStorageSync('student').user,
            ano: options.ano,
            sign: options.sign,
            canClick: true, // 允许用户点击，防止多次提交
            timer2: setInterval(function () {
                that.getAddress()
            }, 20000) // 每20秒刷新一次定位
        })
        this.checkSign()

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.data.timer)
        clearInterval(this.data.timer2)
        console.log("定时器已被清除")
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        wx.setNavigationBarTitle({
            title: '签到签退',
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})